package com.linkoog.devtools.toolwindow_manager;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 *
 */
class ToolWindowPreferenceApplier {
    private final Project project;

    ToolWindowPreferenceApplier(@NotNull Project project) {
        this.project = project;
    }

    void applyPreferencesFrom(@NotNull List<ToolWindowPreference> toolWindowPreferences) {
        if (!project.isDefault()) {
            final ToolWindowManagerProjectComponent projectComponent =
                    project.getComponent(ToolWindowManagerProjectComponent.class);
            final ToolWindowManager manager = ToolWindowManager.getInstance(project);

            for (final ToolWindowPreference toolWindowPreference : toolWindowPreferences) {
                final String id = toolWindowPreference.getId();
                final ToolWindow tw = manager.getToolWindow(id);

                if (tw != null) {
                    final AvailabilityPreference preference = toolWindowPreference.getAvailabilityPreference();

                    switch (preference) {
                        case AVAILABLE:
                            tw.setAvailable(true, null);
                            break;
                        case UNAFFECTED:
                            final AvailabilityPreference defaultAvailability = projectComponent.getDefaultAvailability(id);

                            if (defaultAvailability != null) {
                                tw.setAvailable(defaultAvailability == AvailabilityPreference.AVAILABLE, null);
                            }
                            break;
                        case UNAVAILABLE:
                            tw.setAvailable(false, null);
                            break;
                        default:
                            // Shouldn't be reached...
                    }
                }
            }
        }
    }
}
